package com.example.demo.util;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.log.StaticLog;

/**
 * @description：RSA非对称算法工具类.
 * @author：lw
 * @create_time：2024/2/23
 **/
public class RsaUtil {

//    SecureUtil.md5("admin")  或者 DigestUtil.md5Hex("asds"); 在Hutool 5.x及更高版本中，SecureUtil.md5() 方法已经被弃用，因此使用后者

    public static final  String private_key="MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAOb9ZGDRVKObDjXhGMlymHjn1sXQkwW2Tk/Xx4FnOx9douCOlQ6fgFcsBzMPLjFlMQjBC54MVN/aaviu37xsM3kYM2ORVBg3TrSkOfaIKKFqdt208CQKBWZ0doQe6f+X6kfm4lrRiJoY23dgjtZIGdq5PX/CAVZhabF2BVK//pHBAgMBAAECgYAN0CPDUrFK9wpCk9tUY3a6ADPDgvxPwqJ+qRh2m8TP+SXZY7jQCB8KIJut5J+3d3gpZzXnbJBboAK/vnOqRBZ0pllHfm5gm6aYsg3phlAGLo9RxyP4J8w0SEOzlwhCNlR/51lvBpOVSTZf0iL8HFU7J1rbjHZY4VFC0tmzumQSCwJBAPdPFqXdUcSrYvU1HhGHpWyHT6P+eq9laf5aYOqwO2GfV1hVOQdhwJU8HVvO6/K0aJgKT/FJD0a1ky9u/Oaz2EcCQQDvG30kMK/tvefaUyRvty9JiAt45rI4ZXGHb2iiilazBRKBhVuIhQ/M6FF/fznl2fA8mzVYxKg7P3MIVYbKu9G3AkEAwM2q1XK+7bnD83EO2RHMeNjg0PRzh0xkHwUs66qrEMed2+LNDCE8d9we81VVg6j8phPcETspKrIiZmd7yQxKvwJBAL6uhVXfHe3SjJunwl71D1jsjXmVQHuJKsh/KEq3V/zcBq4T07NDqh4XBydOJrYO3271t81ax264Ytw6mIwEzHECQBa8RaavqgVS+qvtybWgnVauufaJRJvkyq4B7OxR/81u3kk3+vRkN6Nax4Ti6WWd/j8ddhklcIi8Q6jwXBv2GZU=";
    public static final  String public_key="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDm/WRg0VSjmw414RjJcph459bF0JMFtk5P18eBZzsfXaLgjpUOn4BXLAczDy4xZTEIwQueDFTf2mr4rt+8bDN5GDNjkVQYN060pDn2iCihanbdtPAkCgVmdHaEHun/l+pH5uJa0YiaGNt3YI7WSBnauT1/wgFWYWmxdgVSv/6RwQIDAQAB";

    // 先调试调用该方法获取一对服务端的公私钥，然后以静态常量变量的方式写在此类中，把公钥给前端。公钥加密，私钥解密
    public static void getPblicAndPrivateKey(){
        RSA rsa = new RSA();

        //rsa.getPrivateKey();
        //rsa.getPrivateKeyBase64();

        //rsa.getPublicKey();
        //rsa.getPublicKeyBase64();

        StaticLog.info(rsa.getPrivateKeyBase64());
        StaticLog.info(rsa.getPublicKeyBase64());
    }

    public static String  decrypt(String cryptText){
        RSA rsa = new RSA(private_key, null);
        return  rsa.decryptStr(cryptText,KeyType.PrivateKey);
    }

    public static String  decryptS(String cryptText){
        RSA rsa = new RSA(private_key, null);
        byte[] decrypt = rsa.decrypt(cryptText, KeyType.PrivateKey);
        return  StrUtil.str(decrypt, CharsetUtil.CHARSET_UTF_8);
    }

    public static String  encryptS(String text){
        RSA rsa = new RSA(null, public_key);
        byte[] encrypt = rsa.encrypt(text,KeyType.PublicKey);
        return  StrUtil.str(encrypt, CharsetUtil.CHARSET_UTF_8);
    }

}


